<template>
  <div class="headMain" v-if="this.$route.path === '/single/fileSingle'">
    <div :class="!isZoomOut ? 'headStructure' : 'headStructure zoomOut'">
      <div>
        <span v-if="!isZoomOut" class="publicStyle">{{$t('projectDocuments.fileTree')}}</span>
        <p class="arrowLeft" @click="isZoomOut = !isZoomOut">
          <a-icon :type="!isZoomOut ? 'arrow-left' : 'arrow-right'"/>
        </p>
      </div>
      <commElTree v-show="!isZoomOut" ref="commElTree" @noticeInitData='noticeInitData'/>
    </div>
    <div class="headList">
      <div class="title">{{ projectTitle }} (共 {{projectTitleLength}} 个)</div>
      <div class="tableBtn">
        <div>
          <!-- <a-button type="primary" class="width_72" @click="elSelectBtn('download')">{{$t('projectDocuments.download')}}</a-button> -->
          <!-- <a-button type="primary" class="width_72" @click="elSelectBtn('commElupData')" v-if="layerItem"> {{$t('projectDocuments.upload')}}</a-button> -->
          <a-button @click="elSelectBtn('startDocument')" :disabled="startDocumentShow"> {{$t('projectDocuments.startDocumentSign')}}</a-button>
          <!-- <a-button class="width_72" @click="elSelectBtn('paste')" :disabled="parseShow"> 粘贴</a-button> -->
          <!-- <a-button class="width_72" @click="elSelectBtn('commElDelete')" :disabled="commElDeleteDataBen">{{$t('projectDocuments.delete')}}</a-button> -->
          <!-- <a-dropdown>
            <a-button class="style-dropdown-button">
              {{$t('projectDocuments.more')}}
              <a-icon type="dash"/>
            </a-button>
            <a-menu slot="overlay" class="style-dropdown-menu">
              <a-menu-item v-for="item in selectArr" :key="item.key" class="style-btn">
                <a-button class="menuBtn" :disabled="item.show" @click="elSelectBtn(item.key)"> {{
                    item.label
                  }}
                </a-button>
              </a-menu-item>
            </a-menu>
          </a-dropdown> -->
        </div>
        <div>
          <global-search :searchTableData="searchData" @onSearch="onSearch"></global-search>
        </div>
      </div>
      <common-tablecolor
        ref="ref_table"
        :columns="columns"
        :clickIndex="clickIndex"
        :rowClassName="rowClassName"
        :tableData="tableData"
        :selectType="'checkbox'"
        :isRowsSelectVisible="isRowsSelectVisible"
        :loadVisible="loadVisible"
        @selectedRows="selectedRows"
        :this-table-name="''"
        data-row-key="oid"
        @routerContextmenu='routerContextmenu'
        >
        <!-- @routerPage="routerPage" -->
      </common-tablecolor>
    </div>
    <commModal ref="commModal" @initTableData='initTableData'></commModal>
    <!--    鼠标右键-->
    <rightClickEl ref="rightClickEl" @initTableData="initTableData"></rightClickEl>

    <!-- 流程抽屉 -->
    <processDraw @drawClose="drawClose" @drawConfirm="drawConfirm" :processDrawVisible="processDrawVisible" ></processDraw>

  </div>
  <router-view v-else></router-view>
</template>
<script>
import {mapGetters} from 'vuex'
import _ from 'lodash'
import {
  checkDocActionPermission, 
  // getFolderContents
  } from "@/api/fileSingle.js"
import copyACtion from '@/views/singleProject/fileSingle/el-common-js/copy'
// import commonTable from '@/components/common/commonTable'
import commonTablecolor from '@/components/common/commonTableCheckColor'
import globalSearch from "@/components/common/globalSearch"
import commModal from '@/views/singleProject/fileSingle/el-common/comm-modal'
import commElTree from '@/views/singleProject/fileSingle/el-common/comm-el-tree'
import rightClickEl from '@/views/singleProject/fileSingle/el-common/right-click-el'
let userinfo = JSON.parse(sessionStorage.getItem('userInfo'))

import { tableContentData } from "@/json/file.js"
import { getFolderContents } from "@/apiTest/fileApi.js"
import processDraw from '@/views/singleProject/fileSingle/module/processDraw.vue'

export default {
  mixins: [copyACtion],
  components: {
    // commonTable,
    commonTablecolor,
    commModal,
    rightClickEl,
    commElTree,
    globalSearch,
    processDraw
  },
  data() {
    return {
      rowClassNameIndex:"",//点击每行的表格id（使用的数据oid）
      isShowDataBen: false,
      isShowDataBen2: false,
      startDocumentShow: false,//启动签审按钮
      parseShow: false,//复制按钮
      commElDeleteDataBen: false,//删除按钮
      commElRevisionDataBen: false,
      checkInDataBen: false,
      searchData: [],
      tableSelectArr: [],//选中（勾选）的表格数据
      loadVisible: false,
      isRowsSelectVisible: true,
      isZoomOut: false,
      clickIndex:"",
      projectTitle: '',
      projectTitleLength:0,
      layerItem: false,//是否最底层
      tableData: [],
      titleArr2: [
        {id: 'download', number: 10},
        {id: 'startSignWorkflow', number: ''},
        // {id: 'copy', number: ''},
        {id: 'commElDelete', number: 5},
        {id: 'commElRevise', number: 1},
        {id: 'commElRename', number: 16},
        {id: 'commElRevision', number: 7},
        {id: 'cut', number: 12},
        {id: 'paste', number: 2},
        {id: 'commElMobile', number: 12},
        {id: 'checkIn', number: ''},
        {id: 'checkOut', number: ''},
        {id: 'unCheckOut', number: ''},
        {id: 'commElStatusSetting', number: 15},
        {id: 'commElControlAuthority', number: 9}
      ],
      tablefilterData:[], //全部表格数据过滤的介质数组
      treeItem:[],  //放置树节点 和它所有最底层子节点的数组
      // routerHistory:{    //   上个页面过来的路由记录
      //   last:'',
      //   current:'',  
      // }, 
      columns: [
        // {
        // displayName: "",
        // name: "isCheckout",
        // dataType: 'String',
        // width:15,
        // scopedSlots: {customRender: "isCheckout"}
        // },
        {
        displayName: "文件名称",
        enName: 'name',
        name: "name",
        dataType: 'String',
        // width:70,
        scopedSlots: {customRender: "name"}
        },
        {
          displayName: "编号",
          name: "number",
          enName: 'number',
          dataType: 'String',
          // width:50,
          scopedSlots: {
            filterDropdown: "filterDropdown",
            filterIcon: "filterIcon",
            customRender: "customRender"
          }
        },
        {
          displayName: "状态",
          name: "state",
          enName: "state",
          dataType: 'String',
          // width:40,
          scopedSlots: {
            filterDropdown: "filterDropdown",
            filterIcon: "filterIcon",
            customRender: "customRender"
          }
        },
        {
          displayName: "修改者",
          enName: "modifier",
          name: "modifier",
          dataType: 'String',
          // width:40,
          scopedSlots: {
            filterDropdown: "filterDropdown",
            filterIcon: "filterIcon",
            customRender: "customRender"
          }
        }, {
          displayName: "上次修改时间",
          enName: "modifyStamp",
          name: "modifyStamp",
          dataType: 'String',
          // width:70,
          scopedSlots: {
            filterDropdown: "filterDropdown",
            filterIcon: "filterIcon",
            customRender: "customRender"
          }
        },
        {
          displayName: "批准者",
          enName: "approver",
          name: "approver",
          // width:40,
          dataType: 'String'
        },
        {
          displayName: "批准时间",
          enName: "approveDate",
          name: "approveDate",
          // width:70,
          dataType: 'String'
        }
      ],
      
      processDrawVisible: false,
    
    };
  },
  computed: {
    ...mapGetters({
      'fileSingleData': 'fileSingle'
    }),
    selectArr(){
      return [
        // {key: 'commElRevise', label: '修改交付物', show: false},
        {key: 'commElRename', label: this.$t('projectDocuments.reName'), show: false},
        {key: 'commElRevision', label: this.$t('projectDocuments.reVision'), show: false},
        {key: 'cut', label: this.$t('projectDocuments.cut'), show: false},
        {key: 'copy', label: this.$t('projectDocuments.copy'), show: false},
        {key: 'paste', label:this.$t('projectDocuments.paste'), show:'disabled'},
        {key: 'commElMobile', label: this.$t('projectDocuments.mobile'), show: false},
        {key: 'checkIn', label: this.$t('projectDocuments.checkIn'), show: false},
        {key: 'checkOut', label: this.$t('projectDocuments.checkOut'), show: false},
        {key: 'unCheckOut', label: this.$t('projectDocuments.unCheckOut'), show: false},
        {key: 'commElStatusSetting', label: this.$t('projectDocuments.statusSetting'), show: false},
        {key: 'commElControlAuthority', label: this.$t('projectDocuments.controlAuthority'), show: false}
      ]
    },
  },
  watch: {
    'fileSingleData'(val) {
      this.projectTitle = val.treeItem.name
      this.layerItem = val.treeItem.layerItem
    },
    'layerItem'(val){
      if(val==true){
        this.selectArr[4].show = false
      }else{
         this.selectArr[4].show = 'disabled'
      }
    } 
  },
  methods: {
    /**
     * 下拉菜单clik事件
     */
    handleMenuClick(val) {
      if (val.key === 'paste' && !this.fileSingleData.layerItem) return
      this.elSelectBtn(val.key)
    },
    /**
     * 更多 Select 操作
     * key: click事件传的key
     **/
    elSelectBtn(key) {
      if (key === 'startDocument') return this.startDocument()
      // if (key === "startSignWorkflow") return this.startDocument()
      if (key === 'commElupData') {
        this.fileSingleData.needFileStart = true
        this.setFileSingle(this.fileSingleData)
        // return this.$refs.commModal.openElModal(key,this.fileSingleData.tableArr)
      }
      if (key === 'commElupData') return this.$refs.commModal.openElModal(key,this.fileSingleData.tableArr)
      if (key === 'paste') return this.$refs.commModal.openElModal(key,JSON.parse(sessionStorage.getItem('copyFileSingleTableData')))
      /*if (key === 'cut') {
        this.tableSelectArr.forEach(item => {
          item.isCut = true
        })
      }*/
      if (this.tableSelectArr.length < 1) {
        this.$message.error(this.getPrompt(key))
        return
      }
      if (key === 'commElRename' && this.tableSelectArr.length > 1) return this.$message.error('暂不支持批量设置重命名')
      if (key === 'commElStatusSetting' && this.tableSelectArr.length > 1) return this.$message.error('暂不支持批量设置状态')
      if (key === 'commElControlAuthority' && this.tableSelectArr.length > 1) return this.$message.error('暂不支持批量编辑访问控制')
      if (key === 'checkOut' && this.tableSelectArr.length > 1) return this.$message.error('暂不支持批量检出')
      if (key === 'unCheckOut' && this.tableSelectArr.length > 1) return this.$message.error('暂不支持批量撤销检出')
      if (key === 'commElRevise' && this.tableSelectArr.length > 1) return this.$message.error('暂不支持批量修改')
      /*if(key =='commElDelete'){
        this.$refs.commModal.openElModal(key,this.tableSelectArr)
        return
      }*/
      this.$refs.commModal.openElModal(key,this.tableSelectArr)
    },
    /**
     * 初始化数据
     */
    initData(comm) {
      this.tableSelectArr = []
      this.loadVisible = true
      let lastTreeItem = JSON.parse(sessionStorage.getItem('lastTreeCheckedKeys'))
      // let data = {userId: userinfo.loginName, oid: this.fileSingleData.treeItem.oid}
      let data = {
        "userId":"wcadmin",
        "oid":"OR:wt.pdmlink.PDMLinkProduct:86123"
      }
      getFolderContents(data).then(res => {
        // setTimeout(() => {
        //   let res = tableContentData
          if (res && res.data.success == true) {
            this.projectTitleLength = res.data.data.length
            this.tablefilterData = _.orderBy(res.data.data, ['modifyStamp'], ['desc'])//按照创建时间降序排序
            this.tableData = _.orderBy(res.data.data, ['modifyStamp'], ['desc'])//按照创建时间降序排序
            this.searchData = _.orderBy(res.data.data, ['modifyStamp'], ['desc'])//按照创建时间降序排序
            if(comm==true && lastTreeItem !==''){
              this.treeItemFilterData(this.tablefilterData,[lastTreeItem]);
            }
            this.loadVisible = false
          }
        // }, 500);
      })
    },
    //当前树节点和它子级的oid数组 去 过滤表格里面的数据
    treeItemFilterData(tableData, treeItems){
      this.treeItem = [];
      this.f(treeItems)
      // this.initTreeData(treeItems)        //通过当前树节点  拿到树结构里面所有的最下级的树节点文件oid
      let tables= [];
      let arr = [];
      // if (treeItems[0]['oid'].indexOf('Cabinet') != -1) {
      //   arr = tableData
      // } else {
        this.treeItem.forEach((e)=>{
          tables = tableData.filter((i)=>{
            return i.folderOid == e;
          })
          arr.push(...tables)
        })
      // }
      this.projectTitleLength = arr.length
      this.tableData = _.orderBy(arr, ['modifyStamp'], ['desc'])//按照创建时间降序排序
      this.searchData = _.orderBy(arr, ['modifyStamp'], ['desc'])//按照创建时间降序排序
    },
    f(items) {
      items.forEach(item => {
        this.treeItem.push(item.oid)
        if (item.childs) {
          this.f(item.childs)
        }
      })
    },
    //传入树节点的数组，调出它所有最底层子级的oid  (递归调用)
    initTreeData(treeItems){
      treeItems.forEach((e)=>{
        if(e.childs && e.childs.length>0){
          this.initTreeData(e.childs)
        }else{
          this.treeItem.push({oid:e.oid})
        }
      })
      //return arr;
    },
    /**
     * 获取table 选择数据
     */
    selectedRows(val) {
      // console.log('表格选择的数据',val)
      this.tableSelectArr = val//赋值给选择的table数据
      if (val.length == 0) {
        this.startDocumentShow=  false//启动签审按钮
        this.parseShow = false//复制按钮
        this.commElDeleteDataBen = false//删除按钮
        return false
      }
      //当文档未最底层，并且有复制的数据，粘贴才可用
      // this.copyShow = this.getShowData(val, 'paste')
      /*if (this.layerItem && val.length>0) {
        this.copyShow = false
      } else {
        this.copyShow = 'disabled'
      }*/
      //控制按钮权限
      checkDocActionPermission({oid: val[0].oid, actions: this.titleArr2}).then((res) => {
        if (res && res.data.success) {
          let arr = res.data.data
          this.startDocumentShow = this.getShowData(arr, 'startSignWorkflow')
          this.commElDeleteDataBen = this.getShowData(arr, 'commElDelete')
          // this.selectArr[0].show = this.getShowData(arr, 'commElRevise')
          this.selectArr[0].show = this.getShowData(arr, 'commElRename')
          this.selectArr[1].show = this.getShowData(arr, 'commElRevision')
          this.selectArr[2].show = this.getShowData(arr, 'cut')
          // this.selectArr[3].show = this.getShowData(arr, 'copy')
          this.selectArr[3].show = false      //2021-10-14  开放所有复制按钮
          this.selectArr[5].show = this.getShowData(arr, 'commElMobile')
          this.selectArr[6].show = this.getShowData(arr, 'checkIn')
          this.selectArr[7].show = this.getShowData(arr, 'checkOut')
          this.selectArr[8].show = this.getShowData(arr, 'checkIn')
          this.selectArr[9].show = this.getShowData(arr, 'commElStatusSetting')
          this.selectArr[10].show = this.getShowData(arr, 'commElControlAuthority')
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    //获取小组件
    getShowData(arr, key) {
      let data = arr.filter((item) => {
        return item.id === key
      })
      if (!data[0].show == true) {
        return 'disabled'
      } else {
        return false
      }
    },
    /**
     * 全局搜索
     */
    onSearch(tableVal, searchValue) {
      this.loadVisible = true
      if (!searchValue) {
        // 当传过来的数据为空，并且输入条件为空时，重新调用
        this.initData()
      } else {
        this.loadVisible = false
        this.tableData = tableVal
        this.projectTitleLength = this.tableData.length
      }
    },
    /**
     * 子组件通知table 数据更新
     */
    initTableData(type) {
      if (type === 'ControlAuthority') {
        this.$refs.ref_table.selectedRowKeys = []
      }
      let treeDataMax = JSON.parse(sessionStorage.getItem('treeDataMax'));  //拿到整个树节点的缓存
      this.fileSingleData.treeItem  = treeDataMax                           //初始化最外层树节点的oid
      this.initData(true)
    },
    /**
     * comm-el-tree 组件回调
     * item 当前结构树选择的文件夹， layerItem：是否是对底层文件夹
     */
    noticeInitData(val) {
      if(this.tablefilterData && this.tablefilterData.length>0){
        this.treeItem = [];
        this.treeItemFilterData(this.tablefilterData,[this.fileSingleData.treeItem]);
      }else{
        this.initData(this.fileSingleData.treeItem)
      }
    },
    /**
     * commonTable 组件回调方法， val当前点击的哪一行
     */
    routerPage(val) {
      this.fileSingleData.tableArr = [val]
      this.setFileSingle(this.fileSingleData)
      this.setFileSingleTableItem({oid: val.oid, state: val.state,singleOid:val.oid})
      this.$store.commit('SET_PROJECT_FILE_TITLE', val.folderName)
      if(val.type=="项目任务书"){
        this.$router.push({path: "/single/projectPaper/mainTaskBook"})
      }else{
        this.$router.push({path: "fileSingle/examineProject",query:{to:'sigleFile',isShow:true}})
      }
    },
    /**
     * commonTable 组件回调方法，开启鼠标右击弹窗
     * 功能：
     *      start：是否开启 true | false
     *      event：当前点击行e
     *       item：当前点击行元素
     */
    routerContextmenu(start, event, item,index) {
      this.clickIndex = index
      // this.rowClassNameIndex = index
      this.fileSingleData.tableArr = item
      this.setFileSingle(this.fileSingleData)
      this.$refs.rightClickEl.openRightEl(start, event)//鼠标右键点击
    },
    // 点击选中行样式
    rowClassName(record,index){
        return index === this.rowClassNameIndex ? "checkColor":''
        // console.log(record+''+index)
    },
    /**
     * 启动文档
     */
    startDocument(arr) {
      sessionStorage.setItem('fileTableItem', JSON.stringify(this.tableSelectArr))
      // console.log('表头按钮的启动签审',this.tableSelectArr);
      if (arr||this.tableSelectArr.length < 1) return this.$message.error('请选择您所需要启动签审的文档')
      this.fileSingleData.tableArr = (arr || this.tableSelectArr)
      // this.setFileSingle(this.fileSingleData)
      let sessArr = {
        tableArr: (arr || this.tableSelectArr)
      }
      
      sessionStorage.setItem('fileSingleDataByStart',JSON.stringify(sessArr))
      // this.$router.push('fileSingle/fileStart');
      this.processDrawVisible = true


    },

    drawClose() {
      this.processDrawVisible = false
    },
    drawConfirm() {
      this.processDrawVisible = false
      this.$refs.ref_table.selectedRowKeys = []
      this.initData()
    },
    /**
     * 功能：放回点击更多按钮对应的提示
     */
    getPrompt(key) {
      if (key === 'download') return '请选择您所需要下载的文档'
      if (key === 'commElRevise') return '请选择您所需要修改的文档'
      if (key === 'commElupData') return '请选择您所需要上传的文档'
      if (key === 'startDocument') return '请选择您所需要启动文档签审的文档'
      if (key === 'copy') return '请选择您所需要复制的文档'
      if (key === 'commElRename') return '请选择您所需要重名的文档'
      if (key === 'commElDelete') return '请选择您所需要删除的文档'
      if (key === 'commElRevision') return '请选择您所需要修订的文档'
      if (key === 'cut') return '请选择您所需要剪切的文档'
      if (key === 'commElMobile') return '请选择您所需要移动的文档'
      if (key === 'checkIn') return '请选择您所需要检入的文档'
      if (key === 'checkOut') return '请选择您所需要检出的文档'
       if (key === 'unCheckOut') return '请选择您所需要撤销检出的文档'
      if (key === 'commElStatusSetting') return '请选择您所需要设置状态的文档'
      if (key === 'commElControlAuthority') return '请选择您所需要编辑访问权限的文档'
    }
  },
};
</script>
<style lang="less" scoped> 
.headMain {
  display: flex;
  height: calc(100vh - 170px);
  background-color: #fff;
}
.headStructure {
  display: inline-block;
  padding-top: 20px;
  width: 339px;
  flex: 0;
  height: 100%;
  box-sizing: border-box;
  transition: width 0.2s ease-out;
  border-right: 1px solid #EEEEEE;
  & > div {
    font-size: 16px;
  }
  .publicStyle {
    padding-left: 20px;
    font-weight: 600;
  }
  .arrowLeft {
    margin-left: 10px;
    cursor: pointer;
    float: right;
    width: 20px;
    height: 20px;
    box-sizing: border-box;
    font-size: 10px;
    color: #999999;
    text-align: center;
    border: 1px solid #EEEEEE;
    border-right: none;
  }
}
.headList {
  display: inline-block;
  padding: 20px 20px 0 20px;
  // width: 100%;
  width: 0;
  flex: 1;
  box-sizing: border-box;
  .title {
    font-size: 16px;
    font-weight: 600;
  }
}
.tableBtn {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
  & > div:nth-child(1) {
    display: flex;
    .ant-btn {
      margin-right: 10px;
    }
    .styles-select {
      width: 120px;
    }
    // .width_72 {
    //   width: 72px;
    // }
  }
}
.zoomOut {
  width: 30px;
  border: none;
  .arrowLeft {
    border-right: 1px solid #EEEEEE;
  }
}
/deep/ .style-dropdown-button {
  padding: 0;
  padding-left: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 102px;
  .anticon {
    display: inline-block;
    width: 30px;
    height: 32px;
    line-height: 35px;
    font-size: 14px;
    transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
    border-left: 1px solid #d9d9d9;
  }
  // &:hover {
  //   .anticon {
  //     border-left: 1px solid #5f8de3;
  //   }
  // }
}
// /deep/ .ant-dropdown-open {
//   .anticon {
//     border-left: 1px solid #40a9ff;
//   }
// }
.style-dropdown-menu {
  width: 140px;
  background: #FFFFFF;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.20);
  border-radius: 4px;
  box-sizing: border-box;
  & > .ant-dropdown-menu-item {
    cursor: pointer;
    padding-left: 0px;
    font-size: 14px;
    color: #666666;
    height: 32px;
    box-sizing: border-box;
    /*&:hover {
      color: #386BD7;
      background-color: #E8F0FD;
    }*/
  }
  .menuBtn {
    width: 140px;
    border: 0px;
    background-color: transparent;
    line-height: 20px;
    text-align: left;
    padding-left: 24px;
  }
  .menuBtn:hover {
    // color: #386BD7;
    background-color: #E8F0FD;
  }
}
.style-btn,
.style-btn2,
.style-btn3,
.style-btn4 {
  cursor: not-allowed !important;
  color: rgba(0, 0, 0, 0.25) !important;
  background-color: #f5f5f5 !important;
  border-color: #d9d9d9 !important;
  box-shadow: none;
  &:hover {
    color: rgba(0, 0, 0, 0.25) !important;
    background-color: #f5f5f5 !important;
  }
}
</style>